#!/usr/bin/env python
# -*- coding:utf-8 -*-
import time
from django.utils import timezone
from datetime import timedelta,datetime
import collections
from django.shortcuts import render,redirect,reverse
from django.http import JsonResponse
from django.db.models import Count
from django.db.models import Count
from app01 import models
from django.contrib.auth.models import User,Group
from app01.forms.project import projectUserModelForm,StationModelForm,ProductModelForm,projectStationform
from app01.forms.personel import projectDRIform
from django.db.models import Count, F
def wiki_list(request, project_id):
    """ wiki列表 """
    # 获取当前时间
    now = timezone.now()
    # 计算2天前的时间
    two_days_ago = now - timedelta(days=3)

    # 筛选最近2天的数据
    wikis = models.Wiki.objects.filter(
        project_id=project_id,
        create_datetime__gte=two_days_ago

    ).order_by('-create_datetime')
    content={
        'wikis': wikis
        }
    return render(request, 'wiki_list.html', content)
def dashboard(request, project_id):
    """ 概览 """
    form = projectUserModelForm(request)
    stationform=StationModelForm(request)
    project_stationform=projectStationform(request)
    productform=ProductModelForm(request)
    projectDRI_form=projectDRIform(request)

    # 获取项目相关的 Product 和 Station 数据
    products = models.Product.objects.filter(project_id=project_id)
    projectstations = models.ProjectStation.objects.filter(project_id=project_id).order_by('sequence')
    project_DRI_list=models.ProjectDRI.objects.filter(project_id=project_id)

    context = {
        'form': form,
        'stationform': stationform,
        'project_stationform':project_stationform,
        'productform': productform,
        'projectDRI_form': projectDRI_form,
        'products': products,
        'projectstations': projectstations,
        'project_DRI_list': project_DRI_list,
    }
    return render(request, 'dashboard.html',context)
def statistics(request, project_id):
    """ 统计 """
    return render(request, 'statistics.html')
def get_users(request,project_id):
    """获取用户信息"""
    user_list = User.objects.all()
    print('get user list here',user_list)
    users = [{'id': user.id, 'username': user.username} for user in user_list]
    return JsonResponse({'user_list': users})
def get_groups(request,project_id):
    """获取群组信息"""
    group_list = Group.objects.all()
    data = {'groups': {'id': group.id, 'name': group.name} for group in group_list}
    return JsonResponse(data)
def invite_users(request,project_id):
    """邀请用户"""
    if request.method == 'POST':
        user_list=request.POST.getlist('user_ids')
        project_id_from_request=int(request.POST.get('project_id'))
        print(f"Received user_ids: {user_list}")
        print(f"Received project_id: {project_id_from_request}",type(project_id_from_request))
        # project_id=request.tracer.project.id
        print(f"Current project_id: {project_id}",type(project_id))
        if project_id_from_request != project_id:
            return JsonResponse({'status':False,'msg':'项目id不匹配'})
        for user in user_list:
            #判断用户ID是否已经存在项目中
            if models.ProjectUser.objects.filter(project_id=project_id,user_id=user).exists():
                return JsonResponse({'status':False,'msg':'用户已经存在项目中'})
            models.ProjectUser.objects.create(user_id=user,project_id=project_id)
            # 更新项目参与人数，在原来该项目的参与人数上加1
            models.Project.objects.filter(id=project_id).update(join_count=F('join_count')+1)
        return JsonResponse({'status':True,'msg':'添加成功'})
        

    
    return render(request, 'dashboard.html')
def add_station(request,project_id):
    """邀请用户"""
    if request.method == 'POST':
        data=request.POST.dict()
        station_data={'name': data['name'], 'catogory':data['catogory'], 'equip_no': data['equip_no']}
        # print(station_data)  # <QueryDict: {'csrfmiddlewaretoken': ['e50jv0beHscrMbmG0mVmoI6E046o2Zelv5U2XApgJdRNLfFxr03rj8vG0x9LPzm5'], 'name': ['SPI-1'], 'catogory': ['1'], 'equip_no': ['1#']}>
        stationform = StationModelForm(request, data=station_data)
        if stationform.is_valid():
            stationform.instance.project=request.tracer.project
            staion_instance=stationform.save()
            print(staion_instance.get_id())
            project_station_data={'sequence': data['sequence']}
            project_station_form=projectStationform(request,data=project_station_data)
            if project_station_form.is_valid():
                project_station_form.instance.project=request.tracer.project
                project_station_form.instance.station=staion_instance

                project_station_form.save()
                return JsonResponse({'status': True})

    
    return render(request, 'dashboard.html')
def add_product(request,project_id):
    """邀请用户"""
    if request.method == 'POST':
        form = ProductModelForm(request, data=request.POST)
        if form.is_valid():
            form.instance.project=request.tracer.project
            form.save()
            return JsonResponse({'status': True})
        else:
            return JsonResponse({'status': False, 'error': form.errors})

    
    return render(request, 'dashboard.html')
def add_personel(request,project_id):
    """配置线体人员"""
    if request.method == 'POST':
        form = projectDRIform(request, data=request.POST)
        if form.is_valid():
            form.instance.project=request.tracer.project
            form.save()
            return JsonResponse({'status': True})
        else:
            return JsonResponse({'status': False, 'error': form.errors})

    
    return render(request, 'dashboard.html')
def issues_chart(request, project_id):
    """ 在概览页面生成highcharts所需的数据 """
    today = datetime.now().date()
    date_dict = collections.OrderedDict()
    for i in range(0, 30):
        date = today - timedelta(days=i)
        date_dict[date.strftime("%Y-%m-%d")] = [time.mktime(date.timetuple()) * 1000, 0]

    # select xxxx,1 as ctime from xxxx
    # select id,name,email from table;
    # select id,name, strftime("%Y-%m-%d",create_datetime) as ctime from table;
    # "DATE_FORMAT(web_transaction.create_datetime,'%%Y-%%m-%%d')"
    result = models.Issues.objects.filter(project_id=project_id,
                                          create_datetime__gte=today - timedelta(days=30)).extra(
        select={'ctime': "strftime('%%Y-%%m-%%d',web_issues.create_datetime)"}).values('ctime').annotate(ct=Count('id'))

    for item in result:
        date_dict[item['ctime']][1] = item['ct']

    return JsonResponse({'status': True, 'data': list(date_dict.values())})
